export default {
  mounted(el: HTMLElement, binding: any) {
    if (binding.arg === 'parent') {
      el = el.parentElement || el
    }
    el.onmousedown = ev => {
      el.style.cursor = 'move'
      el.style.position = 'fixed'
      // 鼠标按下的位置
      const mouseXStart = ev.clientX
      const mouseYStart = ev.clientY

      // 当前滑块位置
      const rectLeft = el.offsetLeft
      const rectTop = el.offsetTop
      document.onmousemove = e => {
        // 鼠标移动的位置
        const mouseXEnd = e.clientX
        const mouseYEnd = e.clientY
        const moveX = mouseXEnd - mouseXStart + rectLeft
        const moveY = mouseYEnd - mouseYStart + rectTop

        el.style.top = moveY + 'px'
        el.style.left = moveX + 'px'
      }
      document.onmouseup = () => {
        el.style.cursor = ''
        // 取消事件
        document.onmousemove = null
      }
    }
  },
}

//useage
// <div v-drag></div>

// 拖拽子元素来移动父元素
// <div>
//   <div class='header' v-drag:parent>标题</div>
//   <div class='body'>内容</div>
// </div>
